// 简单的选择器封装
var $$ = {
  getEle: function (id) {
    return document.getElementById(id);
  }
};

// 天地图的图层对象
var TianMap = {
  getNormal: function() {
      return L.layerGroup([L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
          maxZoom: 18,
          minZoom: 1
      }), L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
          maxZoom: 18,
          minZoom: 1
      })]);
  },
  getImage: function() {
      return L.layerGroup([L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
          maxZoom: 18,
          minZoom: 1
      }), L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
          maxZoom: 18,
          minZoom: 1
      })]);
  },
  getTerrain: function() {
      return L.layerGroup([L.tileLayer.chinaProvider('TianDiTu.Terrain.Map', {
          maxZoom: 18,
          minZoom: 1
      }), L.tileLayer.chinaProvider('TianDiTu.Terrain.Annotion', {
          maxZoom: 18,
          minZoom: 1
      })]);
  }
};

// 处理扇形角度的对象
var SectorAngle = {
  d2r: function (degree) {
    // 将角度转换为弧度
    return degree * (Math.PI / 180);
  },
  start: function (directAngle, offset) {
    // 根据扇区方向角转换画扇形时的起始角度
    return -(450 - directAngle - offset);
  },
  end: function (directAngle, offset) {
    return -(450 - directAngle + offset);
  },
  transform: function (directAngle) {
    // 图片格式的扇区旋转角度转换
    return (270 + directAngle - 15);
  },
  getRadius: function (level, option) {
    var radius = 0, // 画扇区的默认半径(px)
      cover = 300, // 基站的有效覆盖距离
      scalePx = 90, // 地图比例尺的长度(px)
      scale = {
        10: 10000,
        11: 5000,
        12: 3000,
        13: 1000,
        14: 500,
        15: 300,
        16: 200,
        17: 100,
        18: 50
      };

    if (option !== undefined && A.Util.isObject(option)) {
      radius = option.radius;
      cover = option.cover;
      scalePx = option.scalePx;
      scale = option.scale;
    }

    if (10 <= level && level <= 12) {
      radius = 16;
    } else if (13 <= level && level <= 18) {
      radius = (cover / scale[level]) * scalePx;
    }

    return radius;
  }
};

var CMap = function(mapId, defaultLayer, option, crs) {
  'use strict';

  var crs = crs || L.CRS.EPSG3857,
      defaultLayer = defaultLayer || TianMap.getNormal();

  var map = L.map(mapId, { // 地图
      crs: crs, // web墨卡托
      // crs: L.CRS.EPSG4326,
      doubleClickZoom: false,
      layers: [defaultLayer],
      zoomControl: false,
      attributionControl: false
  });

  this.map = map;
  this.defaultLayer = defaultLayer;

  // // 设置工具
  // this.addZoom();
  // this.addMeasure();
  // this.addCoord();
  // this.addScale();

  return this;
}

CMap.prototype = {
  getMap: function() {
      return this.map;
  },
  setCView: function(center, zoom) {
      this.map.setView(center, zoom);

      return this;
  },
  setLayers: function(base, over, option) {
      var defaultLayer = this.defaultLayer;

      var base = base || { // 切换基础图层的对象
              "地图": defaultLayer,
              "影像": TianMap.getImage(),
              "地形": TianMap.getTerrain()
          },
          over = over || {},
          option = option || {
              position: 'topright',
              collapsed: false
          };

      var layerControl = L.control.layers(base, over, option).addTo(this.map);

      for (var p in over) {
          this.map.addLayer(over[p]);
      }

      return this;
  },
  addMeasure: function() {
      if (L.control.measure !== undefined) {
          // 测距离和面积
          L.control.measure({
              position: 'topleft',
              primaryLengthUnit: 'meters',
              primaryAreaUnit: 'sqmeters',
              // activeColor: '#ABE67E',
              activeColor: '#ff0000',
              // completedColor: '#C8F2BE',
              completedColor: '#ff0000',
              localization: 'cn',
              popupOptions: { className: 'leaflet-measure-resultpopup', autoPanPadding: [10, 10] }
          }).addTo(this.map);

          return this;
      } else {
          // 没有引入插件
          throw new Error('页面没有引入相关js文件');
      }
  },
  addZoom: function() {
      // 缩放
      L.control.zoom({ zoomInTitle: '放大', zoomOutTitle: '缩小' }).addTo(this.map);

      return this;
  },
  addCoord: function() {
      // 经纬度坐标
      L.control.coordinates({
          position: "bottomleft",
          labelTemplateLat: "纬度: {y}",
          labelTemplateLng: "经度: {x}",
          enableUserInput: false
      }).addTo(this.map);

      return this;
  },
  addScale: function() {
      if (L.control.scale !== undefined) {
          L.control.scale({ imperial: false }).addTo(this.map);

          return this;
      } else {
          throw new Error('页面没有引入相关js文件');
      }
  },
  addReturn: function() {
      var map = this.map;

      if (L.easyButton !== undefined) {
          // 地图置中
          L.easyButton('<span class="fa fa-undo"></span>', function(e) {
              map.setView(e._map._lastCenter, 12);
          }, '返回').addTo(map);

          return this;
      } else {
          throw new Error('页面没有引入相关js文件');
      }

  },
  addSlider: function(callee) {
      if (L.control.slider !== undefined) {
          L.control.slider(callee, {
              position: 'topleft',
              max: 1,
              value: 1,
              step: 0.1,
              size: '100px',
              // orientation: 'vertical',
              orientation: 'horizontal',
              id: 'slider',
              title: '透明度',
              logo: 'S'
          }).addTo(this.map);

          return this;
      } else {
          throw new Error('页面没有引入相关js文件');
      }
  }
};

var Ajax = {
  // 请求分担小区
  share: function (loadDetailUrl, loadDetailRequestData, map, stage) {
    $.ajax({
      url: loadDetailUrl,
      method: 'GET',
      dataType: 'json',
      data: loadDetailRequestData,
      success: function (data) {
        console.log('可负载均衡小区列表', data);

        if (data.code === 1) {
          console.log('后台未返回小区信息');
        } else if (data.code === 0 && data.data) {
          const sData = data.data;

          if (!N.Util.isArray(sData)) {
            console.log('返回可负载均衡小区列表数据格式有误');
          } else {
            const n = sData.length;
            // sharedCells = [];

            for (let i = 0; i < n; i++) {
              const dot = map.latLngToContainerPoint([sData[i].lat, sData[i].lng]),
                x = dot.x,
                y = dot.y,
                fillStyle = 'green',
                start = SectorAngle.start(sData[i].an, 30),
                end = SectorAngle.end(sData[i].an, 30),
                radius = 20;

              const circle = new createjs.Shape(),
                g = circle.graphics;

              g.mt(x, y)
                .f(fillStyle)
                .a(x, y, radius, SectorAngle.d2r(start), SectorAngle.d2r(end), true)
                .ef();

              circle.snapToPixel = true;
              stage.addChild(circle);

              stage.update();
            }
          }
        } else {
          console.log('后台未返回小区信息');
        }
      },
      error: function (jqxhr) {
        var errMsg1 = '请求' + this.url + '时出错',
          errMsg2 = '服务器返回http状态码:' + jqxhr.status,
          errMsg3 = '服务器返回内容:' + (jqxhr.responseText ? jqxhr.responseText.trim() : '服务器未响应');

        console.log(errMsg1, errMsg2, errMsg3);
      }
    });
  },
  sectorInfo: function (cellInfoUrl, cellInfoRequestData) {
    $.ajax({
      url: cellInfoUrl,
      method: 'GET',
      dataType: 'json',
      data: cellInfoRequestData,
      success: function (data) {
        console.log('小区详细信息：', data, cellInfoRequestData);

        const $domCellName = $('#cell_name'),
          $domPrbup = $('#prb_up'),
          $domCellType = $('#cell_type'),
          $domCellLevel = $('#cell_level'),
          $domErabNum = $('#erab_num'),
          $domCellPropose = $('#cell_prop'),

          $domDownPrb = $('#down_prb'),
          $domRrc = $('#rrc'),
          $domUpb = $('#upb'),
          $domDownAvg = $('#down_avg'),

          $domUp16qam = $('#up16qam'),
          $domDownPerPrb = $('#downPerPrb'),
          $domCellRation = $('#cell_ration');

        // 检查数据
        if (data.code === 1) {
          console.log('后台未返回一般小区信息');
        } else if (data.code === 0 && data.data) {
          const sData = data.data,
            obj = {
              cellLevel: '',
              cellType: '',
              erabNum: '',
              name: '',
              prbUp: '',
              cellPropose: '',
              downPrb: '',
              rrc: '',
              upB: '',
              downAvg: '',
              downPerPrb: '', // 下行每PRB平均吞吐量
              up16qam: '', // 上行16QAM及以上编码比例
              cellRation: '',

            };

          if (N.Util.isObject(sData)) {
            for (var i in obj) {
              if (sData[i] !== undefined && sData[i] !== null) {
                obj[i] = sData[i];
              } else {
                obj[i] = '';
              }
            }

            const downPrb = obj.downPrb === '' ?
              '' : obj.downPrb.toFixed(2) + '%',
              prbUp = obj.prbUp === '' ?
              '' : obj.prbUp.toFixed(2) + '%',
              rrc = obj.rrc === '' ? '' :
              Math.floor(obj.rrc.toFixed(2)),
              upB = obj.upB === '' ? '' :
              obj.upB.toFixed(2),
              downAvg = obj.downAvg === '' ? '' :
              Math.floor(obj.downAvg.toFixed(2)),
              up16qam = obj.up16qam === '' ? '' :
              obj.up16qam.toFixed(2) + '%',
              downPerPrb = obj.downPerPrb === '' ? '' :
              obj.downPerPrb.toFixed(2),
              cellRation = obj.cellRation === '' ?
              '' : obj.cellRation.toFixed(2) + '%',
              erabNum = obj.erabNum === '' ?
              '' : Math.floor(obj.erabNum.toFixed(2));

            $domCellName.text(obj.name);
            $domPrbup.text(prbUp);
            $domCellType.text(obj.cellType);
            $domCellLevel.text(obj.cellLevel);
            $domErabNum.text(erabNum);
            $domCellPropose.text(obj.cellPropose);

            $domDownPrb.text(downPrb);
            $domRrc.text(rrc);
            $domUpb.text(upB);
            $domDownAvg.text(downAvg);

            $domUp16qam.text(up16qam);
            $domDownPerPrb.text(downPerPrb);
            $domCellRation.text(cellRation);
          } else if (sData === null) {
            $domCellName.text(obj.name);
            $domPrbup.text(obj.prbUp);
            $domCellType.text(obj.cellType);
            $domCellLevel.text(obj.cellLevel);
            $domErabNum.text(obj.erabNum);
            $domCellPropose.text(obj.cellPropose);

            $domDownPrb.text(obj.downPrb);
            $domRrc.text(obj.rrc);
            $domUpb.text(obj.upB);
            $domDownAvg.text(obj.downAvg);

            $domUp16qam.text(obj.up16qam);
            $domDownPerPrb.text(obj.downPerPrb);
            $domCellRation.text(obj.cellRation.toFixed(2) + '%');
          }
        } else if (data.code === 0 && !(data.data)) {
          var emptyText = '';

          $domCellName.text(emptyText);
          $domPrbup.text(emptyText);
          $domCellType.text(emptyText);
          $domCellLevel.text(emptyText);
          $domErabNum.text(emptyText);
          $domCellPropose.text(emptyText);

          $domDownPrb.text(emptyText);
          $domRrc.text(emptyText);
          $domUpb.text(emptyText);
          $domDownAvg.text(emptyText);

          $domUp16qam.text(emptyText);
          $domDownPerPrb.text(emptyText);
          $domCellRation.text(emptyText);
        }
      },
      error: function (jqxhr) {
        var errMsg1 = '请求' + this.url + '时出错',
          errMsg2 = '服务器返回http状态码:' + jqxhr.status,
          errMsg3 = '服务器返回内容:' + (jqxhr.responseText ? jqxhr.responseText.trim() : '服务器未响应');

        console.log(errMsg1, errMsg2, errMsg3);
      }
    });
  },
  sectorLine: function (chartLineUrl, chartLineRequestData, chartLine) {
    const $domCellChartYear = $('#cell_year');

    chartLineRequestData.type = $('#cell_select').val();

    $.ajax({
      url: chartLineUrl,
      method: 'GET',
      dataType: 'json',
      data: chartLineRequestData,
      success: function (data) {
        console.log('小区曲线数据', data);

        // 检查数据
        if (data.code === 1) {
          console.log('后台未返回一般小区信息');
        } else if (data.code === 0 && data.data) {
          var sData = data.data;

          if (!sData.x || !sData.s || !N.Util.isArray(sData.x) ||
            !N.Util.isArray(sData.s) ||
            sData.x.length !== sData.s.length) {
            console.log('后台未返回合法的质差小区统计数据');
          } else {
            // 设置高度
            // $chartLine.css('height', mainHeight * 0.2);

            // chartLine.resize();

            var xData = sData.x,
              seriesData = sData.s,
              seriesDataLength = seriesData.length,
              newSeriesData = [];

            if (xData[0] && xData[0].indexOf('-') !== -1) {
              $domCellChartYear.text(xData[0].split('-')[0] + '年');
            }

            for (var i = 0; i < seriesDataLength; i++) {
              newSeriesData.push(seriesData[i].toFixed(2));
            }

            var option = {
              color: ['#0f0'],
              backgroundColor: '#fff',
              tooltip: {
                trigger: 'axis'
              },
              grid: {
                height: '55%',
                top: 40
              },
              xAxis: {
                type: 'category',
                boundaryGap: false,
                data: xData
              },
              axisLabel: {
                formatter: function (value, index) {
                  if (value !== undefined && value.indexOf('-') !== -1) {
                    var arr = value.split('-');

                    arr.shift();

                    return arr.join("\n");
                  } else {
                    return value;
                  }
                },
                interval: 0
              },
              yAxis: {
                type: 'value',
                axisLabel: {
                  formatter: '{value}'
                }
              },
              series: [{
                type: 'line',
                smooth: true,
                data: newSeriesData,
                markPoint: {
                  data: [{
                    type: 'max',
                    name: '最大值'
                  }]
                },
                areaStyle: {
                  normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: 'rgb(168, 255, 151)'
                    }, {
                      offset: 1,
                      color: 'rgb(244, 255, 241)'
                    }])
                  }
                }
              }]
            };

            chartLine.setOption(option, true);
          }
        }
      },
      error: function (jqxhr) {
        var errMsg1 = '请求' + this.url + '时出错',
          errMsg2 = '服务器返回http状态码:' + jqxhr.status,
          errMsg3 = '服务器返回内容:' + (jqxhr.responseText ? jqxhr.responseText.trim() : '服务器未响应');

        console.log(errMsg1, errMsg2, errMsg3);
      }
    });
  }

};

// Callback
const Callback = {
  sectorMouseOver: function () {
    $('.leaflet-grab').css('cursor', 'pointer');
  },
  sectorMouseOut: function () {
    const $leafletGrab = $('.leaflet-grab');

    $leafletGrab.css('cursor', '-webkit-grab');
    $leafletGrab.css('cursor', '-moz-grab');
    $leafletGrab.css('cursor', 'grab');
  }
};

// 画图对象
var Draw = {
  sector: function (obj) {
    var stage = obj.stage,
      x = obj.x,
      y = obj.y,
      radius = obj.radius,
      start = obj.start,
      end = obj.end,
      anticlock = obj.anticlock,
      fillStyle = obj.fillStyle,
      event = obj.event,
      cellInfoRequestData = obj.cellInfoRequestData,
      cellInfoUrl = obj.cellInfoUrl,
      map = obj.map,
      // addCellInfo = obj.addCellInfo,

      chartLine = obj.chartLine,
      chartLineUrl = obj.chartLineUrl,
      chartLineRequestData = obj.chartLineRequestData,
      loadDetailUrl = obj.loadDetailUrl,
      loadDetailRequestData = obj.loadDetailRequestData;

    var circle = new createjs.Shape(),
      g = circle.graphics;

    // 事件处理回调函数
    var eventCallback = function (e) {
      window.sessionStorage.setItem('clickCellId', cellInfoRequestData.id);

      // console.log(addCellInfo);

      // 绘制可分担小区
      if (cellInfoRequestData.type === 'balance') {
        Ajax.share(loadDetailUrl, loadDetailRequestData, map, stage);
      }

      // 设置小区信息
      Ajax.sectorInfo(cellInfoUrl, cellInfoRequestData);

      // 绘制曲线
      Ajax.sectorLine(chartLineUrl, chartLineRequestData, chartLine);
    };

    // 给图形添加事件监听器
    circle.removeEventListener(event, eventCallback);
    circle.addEventListener(event, eventCallback);


    // 鼠标移入事件
    circle.removeEventListener('mouseover', Callback.sectorMouseOver);
    circle.addEventListener('mouseover', Callback.sectorMouseOver);

    // 鼠标移出事件
    circle.removeEventListener('mouseover', Callback.sectorMouseOut);
    circle.addEventListener('mouseout', Callback.sectorMouseOut);


    g.mt(x, y).f(fillStyle).a(x, y, radius, SectorAngle.d2r(start), SectorAngle.d2r(end), anticlock).ef();
    circle.snapToPixel = true;
    stage.addChild(circle);
  },
  imgCircle: function (obj) {
    var stage = obj.stage,
      x = obj.x,
      y = obj.y,
      event = obj.event,
      info = obj.info,
      requestData = obj.requestData,
      map = obj.map,
      img = obj.img,
      imgWidth = obj.imgWidth,
      imgHeight = obj.imgHeight,
      url = obj.url;

    // console.log(requestData);

    var $leafletGrab = $('.leaflet-grab');

    var circle = new createjs.Bitmap(img);

    circle.set({
      x: x - imgWidth,
      y: y - imgHeight
    });

    // 事件处理回调函数
    var eventCallBack = function (e) {};

    var mouseover = function (e) {
      $leafletGrab.css('cursor', 'pointer');
    };

    var mouseout = function (e) {
      $leafletGrab.css('cursor', '-webkit-grab');
      $leafletGrab.css('cursor', '-moz-grab');
      $leafletGrab.css('cursor', 'grab');
    };

    // 给图形添加事件监听器
    circle.removeEventListener(event, eventCallBack);
    circle.addEventListener(event, eventCallBack);

    // 鼠标移入事件
    circle.removeEventListener('mouseover', mouseover);
    circle.addEventListener('mouseover', mouseover);

    // 鼠标移出事件
    circle.removeEventListener('mouseover', mouseout);
    circle.addEventListener('mouseout', mouseout);

    // 将图形添加到stage
    circle.snapToPixel = true;
    stage.addChild(circle);
  },
  imgSector: function (obj) {
    var stage = obj.stage,
      x = obj.x,
      y = obj.y,
      event = obj.event,
      info = obj.info,
      requestData = obj.requestData,
      map = obj.map,
      img = obj.img,
      angle = obj.angle,
      imgWidth = obj.imgWidth,
      imgHeight = obj.imgHeight,
      url = obj.url;

    var $leafletGrab = $('.leaflet-grab');

    var sector = new createjs.Bitmap(img);

    sector.setTransform(x, y, 1, 1, angle);

    // 事件处理回调函数
    var eventCallBack = function (e) {
      // 点击基站或扇区时，请求单个基站的后台数据，弹出信息
      // LayerAjax.ajax({
      //     url: url,
      //     dataType: 'json',
      //     method: 'POST',
      //     requestData: requestData,
      //     info: info,
      //     map: map
      // });
    };

    var mouseover = function (e) {
      $leafletGrab.css('cursor', 'pointer');
    };

    var mouseout = function (e) {
      $leafletGrab.css('cursor', '-webkit-grab');
      $leafletGrab.css('cursor', '-moz-grab');
      $leafletGrab.css('cursor', 'grab');
    };

    // 给图形添加事件监听器
    sector.removeEventListener(event, eventCallBack);
    sector.addEventListener(event, eventCallBack);

    // 鼠标移入事件
    sector.removeEventListener('mouseover', mouseover);
    sector.addEventListener('mouseover', mouseover);

    // 鼠标移出事件
    sector.removeEventListener('mouseover', mouseout);
    sector.addEventListener('mouseout', mouseout);

    // 将图形添加到stage
    sector.snapToPixel = true;
    stage.addChild(sector);
  }
};